package com.jc.oms.controller.zfl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jc.cds.model.CustomXorder;
import com.jc.common.util.WebUtils;
import com.jc.ds.base.service.BaseService;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.OrderProducts;
import com.jc.ds.model.Xorder;
import com.jc.ds.model.XorderMarge;
import com.jc.framework.enums.*;
import com.jc.oms.controller.BaseController;
import com.jc.service.h5.ShopService;
import com.jc.service.jctask.JcTaskService;
import com.jc.service.logisticscompany.LogisticsCompanyService;
import com.jc.service.order.XorderService;
import com.jc.service.order.XorderServiceImpl;
import com.jc.service.orderproduct.OrderProductsService;
import com.jc.service.systemloglist.SystemLogListService;
import com.jc.service.xordermarge.XorderMargeService;
import com.jc.service.xorderprocess.XorderProcessService;
import com.jc.service.zflservice.ZflCommonUtil;
import com.jc.service.zflservice.ZflProductService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("all")
@Controller
@RequestMapping("zflOrder")
public class ZflOrderController extends BaseController {

    private Long ts = new Date().getTime();
    @Autowired
    private ZflProductService zflProductService;
    @Autowired
    private XorderService xorderService;
    @Autowired
    private LogisticsCompanyService logisticsCompanyService;
    @Autowired
    private SystemLogListService systemLogListService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private XorderMargeService xorderMargeService;
    @Autowired
    private OrderProductsService orderProductsService;
    @Autowired
    private JcTaskService jcTaskService;
    @Autowired
    private XorderProcessService xorderProcessService;

    @RequestMapping(value="/orderMonitor" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> orderMonitor(HttpServletRequest request){
        Map<String,Object> resultMap = new HashMap<>();
        try{
            Map<String,Object> param = WebUtils.ReadAsChars(request);
            String bizContent = param.get("bizContent").toString().substring(1,param.get("bizContent").toString().length()-1);
            String a = bizContent;
            String regex="\\\\";
            Pattern pattern = Pattern.compile(regex); //去掉空格符合换行符
            Matcher matcher = pattern.matcher(a);
            String result = matcher.replaceAll("");
            Map mapType = JSON.parseObject(result,Map.class);
//            Map mapType = param;
            if("DELIVERED".equals(mapType.get("dest"))){
                //查询物流信息
                Map<String,Object> orderMap = new HashMap<>();
                orderMap.put("orderIds",new ArrayList<String>(){{
                    add(mapType.get("orderId").toString());
                }});
                String resultOrderStr = ZflCommonUtil.ZFLHttpUtil(ZFLApi.ORDER_DETAIL.getName(), ZFLApi.ORDER_DETAIL.getDesc(), orderMap);
                systemLogListService.addSystemLog(JSONObject.toJSONString(orderMap), Conclusion.OK, null, LogType.ZFL_GET_ORDER_DETAIL, resultOrderStr);
                Map<String,Object> orderDetail = JSONObject.parseObject(JSONObject.parseObject(resultOrderStr, Map.class).get("bizContent").toString(), Map.class);
                Map<String,Object> orderDTOList = JSONObject.parseObject(JSONObject.parseObject(orderDetail.get("orderDTOList").toString(), List.class).get(0).toString(), Map.class);
                Map<String,Object> orderTrack = JSONObject.parseObject(orderDTOList.get("orderTrack").toString(), Map.class);
                String waybillNo = String.valueOf(orderTrack.get("waybillNo"));
                String logisticsCompany = String.valueOf(orderTrack.get("logisticsCompany"));
                System.out.println("运单号===="+waybillNo);
                //存在物流信息 更新到订单表中
                String orderId = mapType.get("buyerId").toString();
                //修改订单信息
                XorderMarge xorderMargeByChannelOrder = xorderMargeService.getXorderMargeByChannelOrderId(orderId);
                String channelOrderId = "";
                if(xorderMargeByChannelOrder == null) { //无重复推送记录
                    channelOrderId = orderId;
                }else { //有记录
                    channelOrderId = xorderMargeByChannelOrder.getChannelOrderId();
                }
                //查看有没有合并订单的记录
                List<Xorder> orderList = new ArrayList<Xorder>();
                List<XorderMarge> childOrderList = xorderMargeService.getChildOrderList(channelOrderId);
                String parentOrderId = null;
                if(CollectionUtils.isEmpty(childOrderList)) {//无合单记录
                    Xorder queryOrder = new Xorder();
                    queryOrder.setChannelOrderId(channelOrderId);
                    queryOrder.setIsDelete(Booleans.FALSE.getName());
                    List<Xorder> olist = xorderService.queryAll(queryOrder);
                    if(CollectionUtils.isEmpty(olist)) {
                        resultMap.put("code",99999);
                        resultMap.put("message",channelOrderId +  " 订单不存在,无法出库");
                        return resultMap;
                    }
                    if(olist.size() > 1) {
                        resultMap.put("code",99999);
                        resultMap.put("message",channelOrderId +  " 订单在订单表存在两条以上记录,无法出库");
                        return resultMap;
                    }
                    orderList = olist;
                }else {//有合单记录
                    parentOrderId = channelOrderId;
                    for(XorderMarge mg : childOrderList) {
                        Long childOrderId = mg.getOrderId();
                        orderList.add(xorderService.queryById(childOrderId));
                    }
                }
                // 现在每个子订单只有一个产品, 根据SKUID 比较后，更新子订单物流单号.
                String express_codes = "";
                for(Xorder o : orderList) {
                    OrderProducts op = new OrderProducts();
                    op.setOrderId(o.getId());
                    List<OrderProducts> oplist = orderProductsService.queryAll(op);
                    if(CollectionUtils.isNotEmpty(oplist)) {
                        if(OrderStatus.outstorage.getName().equals(o.getOrderStatus())){
                            continue;
                        }
//                        String suppliper_product_id = oplist.get(0).getSupplierProductId();
                        o.setExpressNo(waybillNo);
                        o.setExpressName(logisticsCompany);
                        o.setOrderStatus(OrderStatus.outstorage.getName());
                        o.setUpdateTime(new Date());
                        xorderService.modify(o, false);
                        //订单日志记录表
                        xorderProcessService.addXorderProcess(o.getChannelOrderId(),"商品出库","最福利系统回调",o.getId());
                        express_codes = express_codes  + waybillNo + ",";
                        //推送商城
                        String code = shopService.pushOrder(orderId);
                        if("1".equals(code)){
                            throw new BaseServiceException("订单推送到h5失败 商城orderId:"+orderId);
                        }else{
                            resultMap.put("code","0000");
                        }
                    }
                }
                if(StringUtils.isNotBlank(parentOrderId)) { //更新父订单的状态和运单号
                    Xorder queryOrder = new Xorder();
                    queryOrder.setChannelOrderId(parentOrderId);
                    queryOrder.setIsDelete(Booleans.FALSE.getName());
                    List<Xorder> olist = xorderService.queryAll(queryOrder);
                    if(CollectionUtils.isEmpty(olist)) {
                        resultMap.put("code",99999);
                        resultMap.put("message", parentOrderId +  " 父订单不存在,无法出库");
                        return resultMap;
                    }
                    if(olist.size() > 1) {
                        resultMap.put("code",99999);
                        resultMap.put("message", parentOrderId +  " 父订单在订单表存在两条以上记录,无法出库");
                        return resultMap;
                    }
                    Xorder updateOrder = olist.get(0);
                    updateOrder.setOrderStatus(OrderStatus.outstorage.getName());
                    updateOrder.setExpressNo(express_codes);
                    updateOrder.setUpdateTime(new Date());
                    xorderService.modify(updateOrder, false);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
            return resultMap;
    }
}
